package com.ynet.exception;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSONObject;

/**
 * 异常统一处理
 * @author liuxin
 *
 */
public class MyExceptionHandler implements HandlerExceptionResolver {

	private static Logger logger = LoggerFactory.getLogger(MyExceptionHandler.class);

	@Override
	public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
		
		Map<String, Object> dataMap = new HashMap<String, Object>();

		response.setCharacterEncoding("UTF-8");
		
		response.setContentType("text/html; charset=UTF-8");
		
		if (ex instanceof FinMallException) {
			
			String returnCode = ((FinMallException) ex).getReturnCode();
			Object returnMsg = ((FinMallException) ex).getReturnMsg();
			
			logger.debug("错误代码：  " + returnCode + " 错误信息：" + returnMsg);
			
			dataMap.put("returnCode", returnCode);
			dataMap.put("returnMsg", returnMsg);
			
			try {
				PrintWriter writer = response.getWriter();
				String json = JSONObject.toJSON(dataMap).toString();
				logger.debug(json);
				writer.write(json);
				writer.flush();
				writer.close();
			} catch (IOException e) {
				e.printStackTrace();
				logger.debug("系统繁忙");
			}
			return null;
		} else {
			
			logger.debug("系统繁忙");
			dataMap.put("returnCode", ParamConstants.SYSTEM_ERROR_CODE);
			dataMap.put("returnMsg", ParamConstants.SYSTEM_ERROR_MSG);
			try {
				PrintWriter writer = response.getWriter();
				String json = JSONObject.toJSON(dataMap).toString();
				logger.debug(json);
				writer.write(json);
				writer.flush();
				writer.close();
			} catch (IOException e) {
				e.printStackTrace();
				logger.debug("系统繁忙");
			}
			ex.printStackTrace();
			
			return null;
		}
	}

}
